package com.cqust.dao;

import com.cqust.entity.Card;
import com.cqust.entity.Record;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.util.List;
@Repository
public class RecordDao {
    @Autowired
    JdbcTemplate jdbcTemplate;
    public int insert(Record record)
    {
        String sql="insert into record(cid,consumeTime,consumeMoney) values (?,?,?)";
        Object[] objects=new Object[]{
                record.getCid(),
                record.getConsumeTime(),
                record.getConsumeMoney()
        };
        jdbcTemplate.update(sql,objects);
        sql="select * from record where cid=(select max(cid) from record)";
        RowMapper<Record> rm=new BeanPropertyRowMapper<Record>(Record.class);
        Record record1=jdbcTemplate.queryForObject(sql,rm);
        record.setCid(record1.getCid());
        return record1.getCid();
    }

    public int updateById(Record record)
    {
        String sql="update record set consumeTime=? where rid=?";
        Object[] objects=new Object[]{
                record.getConsumeTime(),
                record.getRid()
        };
        jdbcTemplate.update(sql,objects);
        return 1;
    }

    public int deleteById(int id)
    {
        String sql="delete from record where rid=?";
        jdbcTemplate.update(sql,id);
        return 1;
    }

    public Record selectById(int id)
    {
        String sql="SELECT * FROM record where rid=?";
        RowMapper<Record> rm=new BeanPropertyRowMapper<Record>(Record.class);
        return jdbcTemplate.queryForObject(sql,rm,id);
    }

    public List<Record> selectByCondition(String strWhere)
    {
        String sql="SELECT * FROM record ";
        if(strWhere.trim().length()>0)
        {
            sql=sql+"where "+strWhere;
        }
        RowMapper<Record> rm=new BeanPropertyRowMapper<Record>(Record.class);
        return jdbcTemplate.query(sql,rm);
    }
}
